package com.yh.autobio.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintJob;
import android.print.PrintManager;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.yh.autobio.AppConfig;
import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.api.ErrorHandler;
import com.yh.autobio.api.RetrofitSingleton;
import com.yh.autobio.base.BaseActivity;
import com.yh.autobio.base.BaseFragment;
import com.yh.autobio.common.PLog;
import com.yh.autobio.common.StringUtils;
import com.yh.autobio.common.UIHelper;
import com.yh.autobio.modules.adatper.PackingDetailAdapter;
import com.yh.autobio.modules.bean.CM;
import com.yh.autobio.modules.bean.InvoiceBean;
import com.yh.autobio.modules.bean.InvoiceBody;
import com.yh.autobio.modules.bean.InvoiceHead;
import com.yh.autobio.modules.bean.InvoicePrintBean;
import com.yh.autobio.modules.bean.InvoiceSubBean;
import com.yh.autobio.modules.bean.MessaageEvenBus;
import com.yh.autobio.modules.bean.PackingBean;
import com.yh.autobio.modules.bean.PackingEntryBean;
import com.yh.autobio.modules.bean.ProductBean;
import com.yh.autobio.modules.bean.SimpleBackPage;
import com.yh.autobio.modules.recycleviewutil.RecycleViewDivider;
import com.yh.autobio.modules.ui.empty.EmptyLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yh.autobio.AppConfig.SCN_CUST_ACTION_SCODE;

/**
 * Created by john on 2018/3/12 0012. 10:11
 */

public class PackingDetailFragment extends BaseFragment {

    @InjectView(R.id.recycleview)
    RecyclerView recycleview;
    @InjectView(R.id.swiperefreshlayout)
    SwipeRefreshLayout swiperefreshlayout;
    @InjectView(R.id.error_layout)
    EmptyLayout errorLayout;
    private PackingBean head;
    private PackingDetailAdapter adapter;
    private List<PackingEntryBean> bodys;

    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.scott.ok")) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "打印成功!", Snackbar.LENGTH_SHORT).show();
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View inflate = View.inflate(mActivity, R.layout.fragment_base_recycleview, null);
        ButterKnife.inject(this, inflate);
        initView(inflate);
        initData();
        return inflate;
    }

    @Override
    public void onDestroy() {
        // 解绑
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }


    @Subscribe
    public void onEvent(MessaageEvenBus messge) {
        if (messge.isSuccess())
            Snackbar.make(recycleview, "不要着急，请耐心等待打印结果", Snackbar.LENGTH_SHORT).show();
    }


    @Override
    public void initView(View view) {
        super.initView(view);
        setHasOptionsMenu(true);
        EventBus.getDefault().register(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.scott.ok");
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
        head = (PackingBean) getArguments().getSerializable("HEAD");
        adapter = new PackingDetailAdapter(mActivity);
        adapter.setData(head);
        swiperefreshlayout.setColorSchemeResources(
                R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);

        swiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // TODO: 2016/8/3 下拉刷新
                initData();
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity);
        //设置布局管理器
        recycleview.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
//        layoutManager.setOrientation(layoutManager.VERTICAL);
        //设置增加或删除条目的动画
        recycleview.setItemAnimator(new DefaultItemAnimator());
        recycleview.addItemDecoration(new RecycleViewDivider(mActivity, LinearLayoutManager.VERTICAL, 5, Color.BLACK));
        recycleview.setAdapter(adapter);

    }

    @Override
    public void initData() {
        super.initData();
        showWaitDialog();
        String id = getArguments().getString("ID");
        RetrofitSingleton.getApiService(mActivity).
                FPackingAll(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Itemobserver);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.box_menu, menu);
        MenuItem item = menu.getItem(1);
        item.setVisible(false);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.btn_print:
                print2();
//                print();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }

        ButterKnife.reset(this);
    }

    private void print2() {
        try {
//            JSONObject jObject = new JSONObject();
            InvoicePrintBean matSubBean = new InvoicePrintBean();
            InvoiceBean invoiceHead = new InvoiceBean();
            //设置的ip打印地址
            String set_ip = AppContext.getInstance().getProperty("set_ip");
            if (!StringUtils.isEmpty(set_ip)) {

                invoiceHead.setHostUrl("http://" + set_ip + "/CLodopfuncs.js");
//                invoiceHead.setHostUrl("http://192.168.126.1:18000/CLodopfuncs.js");
//                jObject.put("hostUrl", "http://" + set_ip + "/CLodopfuncs.js");
//                jObject.put("opendirection", "http://" + set_ip + "/images/arrow_right.png");
            } else {
                invoiceHead.setHostUrl("http://192.168.0.170:8000/CLodopfuncs.js");
//                jObject.put("hostUrl", "http://192.168.0.170:8000/CLodopfuncs.js");
//                jObject.put("opendirection", "http://192.168.0.170:8000/images/arrow_right.png");
            }

            invoiceHead.setFbillno(head.getFBillNo());
            invoiceHead.setFReceive(head.getFReceive());
            invoiceHead.setFaddress(head.getFLocation());
            invoiceHead.setFTel(head.getFTel());
            invoiceHead.setFCity(head.getFCity());
            invoiceHead.setFContacts(head.getFContacts());
            invoiceHead.setFMobile(head.getFMobile());
            invoiceHead.setFDate(head.getFDate());
            invoiceHead.setCaseNum(head.getF_xiang_hao());
            List<ProductBean> temps = new ArrayList<ProductBean>();
            for (int i = 0; i < bodys.size(); i++) {
                PackingEntryBean bean1 = bodys.get(i);
                ProductBean bean = new ProductBean();
                String fQty = bean1.getFQty();
                double v = Double.parseDouble(fQty);
                bean.setFDoneNumber((int) v);
                bean.setFEntryName(bean1.getFName());
                bean.setFEntryModel(bean1.getFModel());
                bean.setFBatchNo(bean1.getFBatchNo());
                bean.setFUnitName(bean1.getFUnitName());
                temps.add(bean);
            }
            matSubBean.setBodyList(temps);
            matSubBean.setHeadDetail(invoiceHead);
            List<Integer> list = new ArrayList<>();
            list.add(Integer.parseInt(head.getF_xiang_hao()));
            matSubBean.setBoxsCount(list);
            String s1 = new Gson().toJson(matSubBean).toString();

            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("fB", s1);
            bundle.putString("TYPE", "PACKS");
            intent.putExtras(bundle);
            UIHelper.showSimpleBack(mActivity, SimpleBackPage.WEB, bundle, "打印预览");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    private void print() {
        final WebView webView = new WebView(getActivity());
        WebSettings settings = webView.getSettings();
        webView.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                String set_ip = AppContext.getInstance().getProperty("set_ip");
                set_ip = "http://" + set_ip + "/CLodopfuncs.js";

                InvoicePrintBean matSubBean = new InvoicePrintBean();
                InvoiceBean invoiceHead = new InvoiceBean();
                invoiceHead.setFbillno(set_ip);
                invoiceHead.setFReceive(head.getFCusName());
                invoiceHead.setFaddress(head.getFLocation());
                invoiceHead.setFTel(head.getFTel());
                invoiceHead.setFContacts(head.getFContacts());
                invoiceHead.setFMobile(head.getFMobile());
                invoiceHead.setFDate(head.getFTime());
                List<ProductBean> temps = new ArrayList<ProductBean>();
                for (int i = 0; i < bodys.size(); i++) {
                    PackingEntryBean bean1 = bodys.get(i);
                    ProductBean bean = new ProductBean();
                    String fQty = bean1.getFQty();
                    int v = Integer.parseInt(fQty);
                    bean.setFDoneNumber(v);
                    bean.setFEntryName(bean1.getFName());
                    temps.add(bean);
                }
                matSubBean.setBodyList(temps);
                matSubBean.setHeadDetail(invoiceHead);
                String s1 = new Gson().toJson(matSubBean);
                webView.loadUrl("javascript:showAndroid('" + s1 + "');");
//                createWebPrintJob(view);
            }
        });
// 设置 缓存模式
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.loadUrl("file:///android_asset/printpage2.html");
    }

    private void createWebPrintJob(WebView webView) {

        // Get a PrintManager instance
        PrintManager printManager = (PrintManager) getActivity()
                .getSystemService(Context.PRINT_SERVICE);

        // Get a print adapter instance
        PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();

        // Create a print job with name and adapter instance
        String jobName = getString(R.string.app_name) + " Document";
        PrintJob printJob = printManager.print(jobName, printAdapter,
                new PrintAttributes.Builder().build());

        // Save the job object for later status checking
//        mPrintJobs.add(printJob);
    }

    Observer<List<PackingEntryBean>> Itemobserver = new Observer<List<PackingEntryBean>>() {


        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
            if (swiperefreshlayout.isRefreshing()) {
                swiperefreshlayout.setRefreshing(false);
            }
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(List<PackingEntryBean> result) {
            hideWaitDialog();
            bodys = result;
            if (result != null && result.size() > 0) {
                adapter.setProducts(result);
            }
        }
    };


}
